//
//  DiaryCommentViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/9.
//

import Foundation
import SwiftUI

//日记item
class DiaryItemViewModel : AddDiaryViewModel {
    @Published var changeSuc = false
    @Published var mediaItems: [DiaryItemView.MediaBean] = []
    @Published var commentStatus : Int = 1 //刷新评论使用
    @Published var bean: DiaryBean
    @Published var bubble: BubbleBean?

    init(bean: DiaryBean) {
        self.bean = bean
        super.init()
        self.addObserve(self,  .updateDiary) { (seleInstance, bean: DiaryBean) in
            if self.bean.objectId == bean.objectId {
                //需要同一个才能更新
                seleInstance.bean = bean
                seleInstance.getPictureNet(bean: seleInstance.bean)
                seleInstance.getComment(bean: seleInstance.bean)
            }
        }
        self.addObserve(self,  .updateComment) { (seleInstance, bean: DiaryCommentBean) in
            if self.bean.objectId == bean.diaryId {
                //需要同一个才能更新
                seleInstance.getComment(bean: seleInstance.bean)
            }
        }
//        self.addObserve(self,  .updateBubble) { (seleInstance, bool: Bool) in
//            seleInstance.getBubble(bean: bean)
//        }
        self.addObserve(self,  .updateBubbleComment) { (seleInstance, bean: DiaryBean) in
            if seleInstance.bean.objectId == bean.objectId {
                seleInstance.bean = bean
                seleInstance.getBubble(bean: bean)
            }
        }
    }
    
    func save(diaryBean: DiaryBean) {
        request{
            try await BackupsManager.shared.getDelegateDiary()?.saveDiary(bean: diaryBean)
        } suc: {
            self.changeSuc = true
        } fail: {
            showToast($0.message)
        }
        
    }
    
    /***
     * 删除ai回复
     */
    func delAIReply(diaryBean: Binding<DiaryBean>, aiRoleId: String) {
        request{
            if diaryBean.wrappedValue.isMultiple() {
                if let aiRule = diaryBean.wrappedValue.aiRule, let listAiRole = aiRule.listAiRole {
                    if let index = listAiRole.firstIndex(where: { $0.roleId == aiRoleId }) {
                        var mutableListAiRole = listAiRole
                        mutableListAiRole.remove(at: index)
                        aiRule.listAiRole = mutableListAiRole
                    }
                }
            } else {
                diaryBean.wrappedValue.setChatAiAll(aiRole: nil, value: nil)
            }
            try await BackupsManager.shared.getDelegateDiary()?.saveDiary(bean: diaryBean.wrappedValue)
        } suc: {
            //改临时评论数据, 删除aiRoleId相关的
            diaryBean.wrappedValue.temOther?.removeAll(where: {$0.aiRoleId == aiRoleId})
            self.commentStatus += 1
        } fail: {
            showToast($0.message)
        }
        
    }
    
    
    func getPicture(bean : DiaryBean) {
        mediaItems.removeAll()
        bean.listDiaryPicture?.forEach {
            if let mediaItem = DiaryExt.getMediaItem($0) {
                let bean = DiaryItemView.MediaBean()
                bean.media = mediaItem
                bean.picture = $0
                mediaItems.append(bean)
                
            }
        }
    }
    
    //请求网络
    func getPictureNet(bean : DiaryBean) {
        request {
            let list = [bean]
            try await DiaryExt.dealPicture(list, true)
            return ""
        } suc: { _ in
            self.getPicture(bean: bean)
        } fail: {
            showToast($0.message)
        }
    }
    
    //请求网络
    func getComment(bean : DiaryBean) {
        request {
            try await Task.delay(2000) //避免过快，导致评论占有了一个空白区域
            let list = [bean]
            bean.temOther = nil
            try await DiaryExt.dealComment(list)
            return ""
        } suc: { _ in
            withAnimation { //给评论加个动画
                self.commentStatus += 1
                showLog("刷新评论")
            }
        } fail: { _ in
        }
        
    }
    
    func getBubble(bean : DiaryBean) {
        request(isLoading: false) {
            var bubbleId = bean.bubbleId
            if (bubbleId ?? "").isEmpty == true {
                if bean.roleType == IRoleType.BOT.rawValue {
                    let role = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: bean.roleId)
                    bubbleId = role?.bubbleCommentId
                } else {
                    bubbleId = userManager.getExtraConfig().bubbleCommentId
                }
            }
            return BubbleExt.getBubble(id: bubbleId)
        } suc: { bubble in
            self.bubble = bubble
        } fail: { _ in
        }
        
    }
}
